//
//  BLDatePickView.m
//  Byelone
//
//  Created by Qi Liu on 2021/2/7.
//

#import "BLDatePickView.h"
#import "PGPickerView.h"


typedef void(^DatePickBlock)(NSDictionary * _Nullable dateDic);

@interface BLDatePickView ()<PGPickerViewDelegate, PGPickerViewDataSource>
{
    NSInteger yearRange;
    NSInteger dayRange;
    NSInteger startYear;
    NSInteger selectedYear;
    NSInteger selectedMonth;
    NSInteger selectedDay;
    NSInteger selectedHour;
    NSInteger selectedMinute;
    NSInteger selectedSecond;
    NSCalendar *calendar;
}
@property(nonatomic,strong) UIView * baseView;
@property(nonatomic,strong) PGPickerView * pickView;
@property (nonatomic, strong) NSArray *bigArray;
@property(nonatomic,strong) UILabel * titleLabel;
@property(nonatomic,strong) UIButton * cancelBtn;
@property(nonatomic,strong) UIButton * sureBtn;
@property (nonatomic, assign) NSInteger provinceIndex,cityIndex;
@property(nonatomic,copy) DatePickBlock  dateBlock;

@end

@implementation BLDatePickView


+(void)showDatePickView:(void(^)(NSDictionary * dateDic))block{
    BLDatePickView * pickView = [[BLDatePickView alloc]initWithFrame:BL_WINDOW_FRAME];
    pickView.dateBlock = block;
    [BL_WINDOW addSubview:pickView];
}

-(NSArray * )bigArray{
    if (_bigArray == nil) {
        _bigArray = [BLUserManager shareUser].commonInfo.areaList;
    }
    return _bigArray;
}


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(disMissView)];
        [self addGestureRecognizer:tap];

        [self setUp];
    
        NSCalendar *calendar0 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        NSInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        comps = [calendar0 components:unitFlags fromDate:[NSDate date]];
        NSInteger year=[comps year];
        startYear = 1950;
        yearRange = 200;
        
        [self setCurrentDate:[NSDate date]];
        
    }
    return self;
}

- (void)setCurrentDate:(NSDate *)currentDate{
    NSLog(@"dddddd = %@", currentDate);
    //获取当前时间
    NSCalendar *calendar0 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    comps = [calendar0 components:unitFlags fromDate:currentDate];
    NSInteger year = [comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    NSInteger second = [comps second];
    
    selectedYear = year;
    selectedMonth = month;
    selectedDay = day;
    selectedHour = hour;
    selectedMinute = minute;
    selectedSecond = second;
    
    dayRange = [self isAllDay:year andMonth:month];
    
    [_pickView selectRow:year-startYear inComponent:0 animated:true];
    [_pickView selectRow:month-1 inComponent:1 animated:true];
    [_pickView selectRow:day-1 inComponent:2 animated:true];

}


-(void)disMissView{
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}



-(void)sureClick{
    if (_dateBlock) {
        
        
        NSString * timeString = [NSString stringWithFormat:@"%ld-%.2ld-%.2ld",selectedYear,selectedMonth,selectedDay];
        double longtimeSp;
        NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
        formatter.dateFormat=@"YYYY-MM-dd";
        NSDate*date=[formatter dateFromString:timeString];
        longtimeSp =(long)[date timeIntervalSince1970];//时间戳
        NSString * timestampString = [NSString stringWithFormat:@"%f",longtimeSp];
        
        NSDictionary * dateDic = @{@"dateString":timeString,
                                                  @"timestamp":timestampString
        };
        _dateBlock(dateDic);
    }
    
    NSLog(@"%@",[NSString stringWithFormat:@"%ld-%.2ld-%.2ld",selectedYear,selectedMonth,selectedDay]);
    
    [self disMissView];
}


#define baseViewH 260
#define blueViewW 320
#define pickViewW 120
-(void)setUp{
    self.backgroundColor = BL_COLOR_ALPHA;
    _provinceIndex = 0;
    _cityIndex = 0;
    
    UIView * baseView = [[UIView alloc]initWithFrame:CGRectMake(0, BL_WINDOW_HEIGHT-baseViewH, BL_WINDOW_WIDTH, baseViewH)];
    baseView.backgroundColor = [UIColor whiteColor];
    _baseView = baseView;
    [self addSubview:baseView];

    
    UIView * blueView = [[UIView alloc]init];
    blueView.backgroundColor = [UIColor chColorWithHexString:@"#E7E8FF"];
    blueView.frame = CGRectMake((BL_WINDOW_WIDTH - blueViewW)/2, (CGRectGetHeight(baseView.frame) - 34)/2, 320, 34);
    blueView.layer.cornerRadius = 10;
    blueView.layer.masksToBounds = YES;
    [baseView addSubview:blueView];
    
    UIButton * cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    cancleBtn.titleLabel.textColor = [UIColor whiteColor];
    [cancleBtn setBackgroundColor:[UIColor chColorWithHexString:@"#C3C3C3"]];
    cancleBtn.layer.cornerRadius = 8.75;
    cancleBtn.layer.masksToBounds = YES;
    [cancleBtn addTarget:self action:@selector(disMissView) forControlEvents:UIControlEventTouchUpInside];
    _cancelBtn = cancleBtn;
    [baseView addSubview:cancleBtn];
    
    
    UILabel * titleLable = [[UILabel alloc]init];
    titleLable.text = @"选择预约时间";
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.font = [UIFont systemFontOfSize:12];
    titleLable.textColor = [UIColor chColorWithHexString:@"#555555"];
    [baseView addSubview:titleLable];
    _titleLabel = titleLable;
    
    
    UIButton * sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    sureBtn.titleLabel.textColor = [UIColor whiteColor];
    [sureBtn setBackgroundColor:[UIColor chColorWithHexString:@"#6C72F5"]];
    sureBtn.layer.cornerRadius = 8.75;
    sureBtn.layer.masksToBounds = YES;
    [sureBtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    _sureBtn = sureBtn;
    [baseView addSubview:sureBtn];
    
    
    _pickView = [[PGPickerView alloc]initWithFrame:CGRectMake(30, (CGRectGetHeight(baseView.frame)-pickViewW)/2, BL_WINDOW_WIDTH-60, pickViewW)];
    _pickView.delegate = self;
    _pickView.dataSource = self;
    _pickView.type = PGPickerViewLineTypelineSegment;
    
//    [_pickView selectRow:0 inComponent:0 animated:true];
//    [_pickView selectRow:0 inComponent:1 animated:true];
//    [_pickView selectRow:3 inComponent:2 animated:true];
    _pickView.rowHeight = 45;
    _pickView.isHiddenMiddleText = false;
    //设置线条的颜色
    _pickView.lineBackgroundColor = [UIColor clearColor];
    //设置选中行的字体颜色
    _pickView.textColorOfSelectedRow = [UIColor chColorWithHexString:@"#6C72F5"];
    //设置未选中行的字体颜色
    _pickView.textColorOfOtherRow = [UIColor chColorWithHexString:@"#888888"];
    [baseView addSubview:_pickView];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    _cancelBtn.frame = CGRectMake(22, 18.5, 40, 20);
    _titleLabel.frame = CGRectMake(0, 18.5, 150, 20);
    _titleLabel.middleX = _baseView.middleX;
    _sureBtn.frame = CGRectMake(BL_WINDOW_WIDTH-62, 18.5, 40, 20);
}


#pragma UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(PGPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(PGPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    switch (component) {
        case 0:
        {
            return yearRange;
        }
         
        case 1:
        {
            return 12;
        }
         
        case 2:
        {
            return dayRange;
        }
         
        default:
            return 0;;
    }
}
#pragma UIPickerViewDelegate
- (nullable NSString *)pickerView:(PGPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
   
    switch (component) {
        case 0:
            return [NSString stringWithFormat:@"%ld年",(long)(startYear + row)];
        case 1:
            return [NSString stringWithFormat:@"%ld月",(long)row+1];
        case 2:
            return [NSString stringWithFormat:@"%ld日",(long)row+1];
        default:
            return @"";;
    }
//
//
//    if (component == 0) {
//
//    }
//    if (component == 1) {
//
//    }
//    return @"";
}

- (void)pickerView:(PGPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            selectedYear=startYear + row;
            dayRange=[self isAllDay:selectedYear andMonth:selectedMonth];
            [pickerView reloadComponent:2];
        }
            break;
        case 1:
        {
            selectedMonth=row+1;
            dayRange=[self isAllDay:selectedYear andMonth:selectedMonth];
            [pickerView reloadComponent:2];
        }
            break;
        case 2:
        {
            selectedDay=row+1;
        }
            break;
            
        default:
            break;
    }
    
  
   
}

- (NSInteger)isAllDay:(NSInteger)year andMonth:(NSInteger)month
{
    int day=0;
    switch(month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day=31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day=30;
            break;
        case 2:
        {
            if(((year%4==0)&&(year%100!=0))||(year%400==0))
            {
                day=29;
                break;
            }
            else
            {
                day=28;
                break;
            }
        }
        default:
            break;
    }
    return day;
}


@end
